package com.movie.config;

import com.movie.beans.SysUser;
import com.movie.service.LoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private LoginService loginService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        Subject subject = SecurityUtils.getSubject();;
//        // 角色列表
        SysUser user = (SysUser) subject.getPrincipal();
//        System.out.println(user+"2");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        // 管理员拥有所有权限
//        if (user.getRole().equals("1"))
//        {
//            info.addRole("admin");
//            info.addStringPermission("*:*:*");
//        }
//        return info;
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        System.out.println("认证");
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username=upToken.getUsername();
        String password="";
        if (upToken.getPassword() != null)
        {
            password = new String(upToken.getPassword());
        }

        SysUser user = null;
        try
        {
            user = loginService.login(username,password);
        }
        catch (IncorrectCredentialsException e)
        {
            throw new IncorrectCredentialsException("密码错误");
        }
        catch (DisabledAccountException e){
            throw new DisabledAccountException("账号已被禁用");
        }
        catch (UnknownAccountException e)
        {
            throw new UnknownAccountException("用户不存在");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
        return info;
    }
}
